package no.ntnu.fp.net;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 
 * Initialize and create database connection, with final specified parameters
 *
 */
public class DBConnection {
	
	private Connection connection;
	
	private final String USERNAME = "calendar30";
	private final String PASSWORD = "calendar30";
	private final String DATABASEURL = "jdbc:mysql://db4free.net/calendarsystem";
	
	
	/**
	 * Constructor to initiate and save database connection
	 */
	public DBConnection() {
		try {
			this.connection = DriverManager.getConnection(
											DATABASEURL,
											USERNAME,
											PASSWORD);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * Method for querying the database for a result using SELECT
	 * @param queryString <code>ResultSet</code>
	 * @return
	 * @throws SQLException 
	 */
	public ResultSet selectFromDatabase(String queryString) 
										throws SQLException {
			
		Statement statement = this.connection.createStatement();	
		
		return statement.executeQuery(queryString);
		
	}
	
	
	/**
	 * Method to modify database using INSERT, UPDATE or DELETE
	 * @param queryString
	 * @throws SQLException
	 */
	public void modifyDatabase(String queryString) throws SQLException {
		
		PreparedStatement statement = this.connection.prepareStatement(queryString);
		statement.executeUpdate();
	}
	
	
	/**
	 * Closes database connection.
	 * @throws SQLException
	 */
	public void close() throws SQLException {
		this.connection.close();
	}

}

